<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { useUserStore } from '@/stores/user'
  import RoomStatus from './components/room-status.vue'
  // #ifdef APP||H5
  import { io, type Socket } from 'socket.io-client'
  // #endif
  import { nextTick, ref } from 'vue'
  import { orderDetailApi } from '@/apis/consult'
  import type { OrderDetail } from '@/types/consult'
  import type { MsgData, MsgItem, SendChatMsgParams } from '@/types/room'
  import PatientInfo from './components/patient-info.vue'
  import NotifyInfo from './components/notify-info.vue'
  import MessageInfo from './components/message-info.vue'
  import { uploadImageApi } from '@/apis/user'
  import PrescriptionInfo from './components/prescription-info.vue'
  import RateInfo from './components/rate-info.vue'

  const pageParams = defineProps<{
    orderId: string
    payResult: 'true' | 'false'
    type: string
  }>()

  if (pageParams.payResult === 'false') {
    uni.showToast({
      title: '支付失败',
      icon: 'none',
    })
    setTimeout(() => {
      uni.reLaunch({ url: '/pages/my/index' })
    }, 1500)
  }
  // 问诊订单详情
  const orderDetail = ref({} as OrderDetail)

  const getOrderDetail = async () => {
    const data = await orderDetailApi(pageParams.orderId)
    console.log('问诊订单详情：', data)
    orderDetail.value = data
  }
  getOrderDetail()

  // 消息列表
  const messageList = ref<MsgItem[]>([])

  const getIndex = () => {
    uni.switchTab({
      url: '/pages/index/index',
    })
  }

  //输入框消息
  const textMessage = ref('')

  const store = useUserStore()

  // #ifdef APP||H5
  // 2. 建立连接
  const socket = io('https://consult-api.itheima.net', {
    auth: { token: 'Bearer ' + store.token },
    query: { orderId: pageParams.orderId },
    transports: ['websocket', 'polling'],
    timeout: 5000,
  })

  socket.on('connect', () => {
    // 建立连接成功
    console.log('连接建立成功')
  })

  socket.on('error', (event) => {
    // 错误异常消息
    console.log('出现错误')
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('断开连接')
  })

  socket.on('statusChange', () => {
    getOrderDetail()
  })

  // 1.3 接收消息
  // 1.3.1 消息列表
  socket.on('chatMsgList', async (res: MsgData) => {
    // 没有返回数据
    if (res.code !== 10000) return
    // 提取列表数据
    if (res.data?.length) {
      // 后端对消息进行了分段，渲染时要遍历所有分段
      res.data.forEach((item) => {
        // 把每个分段的消息都追加到数组中
        messageList.value.push(
          // 按日期分段
          {
            createTime: item.createTime!,
            msg: {
              content: item.createTime,
            },
            msgType: 31,
          },
          // 分段的聊天数据
          ...item.items!
        )
      })
    }
    console.log('历史消息：', messageList.value)
    await nextTick(() => {
      // 滚动到底部
      activeIndex.value = `item-${messageList.value.length - 1}`
    })
  })

  // 3. 接收回复消息
  socket.on('receiveChatMsg', async (message: MsgItem) => {
    // 修改消息为已读
    socket.emit('updateMsgStatus', message.id)
    // 接收到的消息追加到消息列表中
    messageList.value.push(message)
    await nextTick(() => {
      // 滚动到底部
      activeIndex.value = `item-${messageList.value.length - 1}`
    })
  })

  //发送消息
  const sendMessage = () => {
    if (textMessage.value.trim() === '') {
      return uni.showToast({
        title: '请输入消息',
        icon: 'none',
      })
    }

    socket.emit('sendChatMsg', {
      from: store.userId,
      to: orderDetail.value.docInfo.id,
      msgType: 1,
      msg: { content: textMessage.value },
    } as SendChatMsgParams)

    //messageList.value.push(textMessage)
    textMessage.value = ''
  }

  // 发送图片
  const sendImage = async () => {
    // 1. 选取图片
    const res = await uni.chooseImage({ count: 1 })
    // 如果有图片
    if (res.tempFilePaths[0]) {
      // 2. 上传图片
      const imageInfo = await uploadImageApi(res.tempFilePaths[0])
      // 3. 发送图片消息
      socket.emit('sendChatMsg', {
        from: store.userId, // 患者/用户 id
        to: orderDetail.value.docInfo.id, // 医生 id
        msgType: 4, // 4图片类型
        msg: {
          picture: imageInfo,
        },
      } as SendChatMsgParams)
    }
  }
  // #endif
  const activeIndex = ref('')
</script>

<template>
  <view class="room-page">
    <RoomStatus
      v-if="orderDetail.status"
      :status="orderDetail.status"
      :status-value="orderDetail.statusValue"
      :countdown="orderDetail.countdown"
    ></RoomStatus>
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="activeIndex"
    >
      <view
        class="message-container"
        v-for="(item, index) in messageList"
        :key="item.id"
        :id="`item-${index}`"
      >
        <view>
          <PatientInfo v-if="item.msgType === 21" :info="item.msg?.consultRecord!" />
          <PrescriptionInfo v-else-if="item.msgType === 22" :info="item.msg?.prescription!" />
          <RateInfo
            v-else-if="item.msgType === 23"
            :order-id="pageParams.orderId"
            :doctor-id="orderDetail.docInfo?.id"
          ></RateInfo>
          <rate-info
            :evaluateDoc="item.msg?.evaluateDoc"
            has-evaluate
            v-else-if="item.msgType === 24"
          />
          <NotifyInfo v-else-if="[31, 32, 33].includes(item.msgType!)" :type="item.msgType"
            >{{ item.msg?.content }}
          </NotifyInfo>
          <MessageInfo
            v-else-if="[4,1].includes(item.msgType!)"
            :info="item"
            :type="item.msgType"
          ></MessageInfo>
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="orderDetail.status < 4">
        <uni-easyinput
          :disabled="orderDetail.status !== 3"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
          v-model="textMessage"
          @confirm="sendMessage"
        />
        <view class="image-button">
          <uni-icons @click="sendImage" size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button" @click="getIndex">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './index.scss';
</style>
